﻿module Sustainalytics.Controversies {

    import Company = Sustainalytics.Company;
    import Common = Sustainalytics.Common;

    export class ControversyGroupAssessmentsController {


        public serialChartOptionsDictionary: Common.Dictionary<Charts.SerialChartOptions> = new Common.Dictionary<Charts.SerialChartOptions>();

        private controversyIndicators: ControversyIndicatorDto[] = null;
        private comparisonGroupControversies: ComparisonGroupControversyDto[] = null;

        private controversiesCtrl: ControversiesController;

        public dataChartIsLoading: boolean = true;
        public isInitLoading: boolean;

        private userId: string;

        private location: any;

        public notFoundMessage: string ='';
        public noClaims: boolean = false;

        constructor(
            private $rootScope: ng.IScope,
            private $scope: Company.ICompanyBasedScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,

            private RoutingService: Routing.IRoutingService,
            private ControversiesService: IControversiesService) {

            var ctx = this;

            ctx.controversiesCtrl = $scope['controversies'];

            ctx.location = ctx.RoutingService.getRouteEngineAdapter().getCurrentPath();

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.init();
        }

        private init(): ng.IPromise<any> {
            var ctx = this;

            ctx.isInitLoading = true;
            ctx.$rootScope['loading'] = true;

            ctx.serialChartOptionsDictionary = new Common.Dictionary<Charts.SerialChartOptions>();



            var def = ctx.$q.defer();

            var promise1 = ctx.getControversyIndicators();
            var promise2 = ctx.getComparisonGroupControversies();

            ctx.$q.all([promise1, promise2]).then(
                // success
                function () {

                    if (ctx.controversyIndicators) {
                        $.each(ctx.controversyIndicators, function (index, ci) {

                            var chartScores = ctx.getDefaultChartScores();

                            $.each(chartScores, function (index, chartScore) {

                                if (ctx.comparisonGroupControversies) {
                                    $.each(ctx.comparisonGroupControversies, function (index, cgc) {
                                        if (cgc.category == chartScore.category && cgc.controversyIndicatorNumber == ci.number) {
                                            chartScore.percent = cgc.percent;
                                        }
                                    });
                                }

                                if (chartScore.category == ci.answerCategory) {
                                    chartScore.color = "#D4A017"
                                }
                            });

                            ctx.serialChartOptionsDictionary.add(ci.number, ctx.createSerialChartOptions(ci.name, chartScores));
                        });
                    }

                    
                    //ctx.serialChartOptionsDictionary.add('E.2.2', ctx.createSerialChartOptions('Environmental Supply Chain Incidents'));
                    //ctx.serialChartOptionsDictionary.add('E.3.2', ctx.createSerialChartOptions('Product & Service Incidents'));

                    //ctx.serialChartOptionsDictionary.add('S.1.7', ctx.createSerialChartOptions('Employee Incidents'));
                    //ctx.serialChartOptionsDictionary.add('S.2.3', ctx.createSerialChartOptions('Social Supply Chain Incidents'));
                    //ctx.serialChartOptionsDictionary.add('S.3.3', ctx.createSerialChartOptions('Customer Incidents'));
                    //ctx.serialChartOptionsDictionary.add('S.4.3', ctx.createSerialChartOptions('Society & Community Incidents'));

                    //ctx.serialChartOptionsDictionary.add('G.1.5', ctx.createSerialChartOptions('Business Ethics Incidents'));
                    //ctx.serialChartOptionsDictionary.add('G.2.13', ctx.createSerialChartOptions('Governance Incidents'));
                    //ctx.serialChartOptionsDictionary.add('G.3.4', ctx.createSerialChartOptions('Public Policy Incidents'));


                    ctx.$rootScope['loading'] = false;


                    def.resolve();
                },
            // error
            function (reason) {

                ctx.$rootScope['loading'] = false;

                ga('create', 'UA-4379897-6', {
                    'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                });

                ga('globalAccess.send', 'exception', { 'exDescription': 'Controversies: ControversyGroupAssessments Controller -> Error initializing' });

                def.reject(reason);
            });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;
            });

            return promise;
        }

        private getControversyIndicators(): ng.IPromise<any>  {
            var ctx = this;

            if (!ctx.$scope.currentCompany) {
                return ctx.$q.when(null);
            }

            var promise = ctx.ControversiesService.getControversyIndicators(ctx.$scope.currentCompany.id)

            promise.then(function (res) {

                ctx.controversyIndicators = res;

            },
            function (reason) {
                console.log('Failed: ' + reason);
            });

            return promise;
        }

        private getComparisonGroupControversies(): ng.IPromise<any> {
            var ctx = this;

            if (!ctx.$scope.currentCompany) {
                return ctx.$q.when(null);
            }

            var promise = ctx.ControversiesService.getComparisonGroupControversies(ctx.$scope.currentCompany.id);

            promise.then(function (res) {

                ctx.comparisonGroupControversies = res;

            }, function (reason) {
                console.log('Failed: ' + reason);
            });

            return promise;
        }

        private getDefaultChartScores(): ChartScoreDto[] {
            var chartScores = [
                {
                    "category": 0,
                    "categoryLabel": "none",
                    "percent": 0,
                    "color": "#B6B6B4"
                },
                {
                    "category": 1,
                    "categoryLabel": "Category 1",
                    "percent": 0,
                    "color": "#B6B6B4"
                },
                {
                    "category": 2,
                    "categoryLabel": "Category 2",
                    "percent": 0,
                    "color": "#B6B6B4"
                },
                {
                    "category": 3,
                    "categoryLabel": "Category 3",
                    "percent": 0,
                    "color": "#B6B6B4"
                },
                {
                    "category": 4,
                    "categoryLabel": "Category 4",
                    "percent": 0,
                    "color": "#B6B6B4"
                },
                {
                    "category": 5,
                    "categoryLabel": "Category 5",
                    "percent": 0,
                    "color": "#B6B6B4"
                }
            ];
            return chartScores;
        }

        public getSerialChartOptions(controversyIndicatorNumber: string): Charts.SerialChartOptions {
            var ctx = this;

            var chartOptions: Charts.SerialChartOptions = ctx.serialChartOptionsDictionary.getValue(controversyIndicatorNumber);

            //chartOptions.dataProvider = chartScores;
            
            return chartOptions;
        }

        private createSerialChartOptions(title: string, chartScores: ChartScoreDto[]): Charts.SerialChartOptions {
            var options: any =
                {
                    "type": "serial",
                    "pathToImages": "http://cdn.amcharts.com/lib/3/images/",                    
                    "categoryField": "categoryLabel",
                    "marginTop": 10,
                    "startDuration": 1,
                    "categoryAxis": {
                        "gridPosition": "start",
                        "autoGridCount": false,
                        "fontSize": "8",
                        "ignoreAxisWidth": false,
                        "labelRotation": 25
                    },
                    "trendLines": [],
                    "graphs": [
                        {
                            "colorField": "color",
                            "fillAlphas": 1,
                            "id": "AmGraph-1",
                            "lineColorField": "color",
                            "title": "graph 1",
                            "type": "column",
                            "valueField": "percent"
                        }
                    ],
                    "guides": [],
                    "valueAxes": [
                        {
                            "id": "ValueAxis-1",
                            "maximum": 100,
                            "autoGridCount": false,
                            "fontSize": 9,
                            "unit": "%",
                        }
                    ],
                    "allLabels": [],
                    "balloon": {},
                    //"titles": [{
                    //        "id": "Title-1",
                    //        "size": 9,
                    //        "text": title,
                    //        "titleBold": false
                    //}],
                    "dataProvider": chartScores
                };

            return options;
        }
    }


    export var controllerName = 'ControversyGroupAssessmentsController';

    angular.module(controversiesModuleName).controller(controllerName,
        ['$rootScope', '$scope', '$q', '$timeout', 'RoutingService', 'ControversiesService', ControversyGroupAssessmentsController]);
} 